<?php 
/**
* @orm tableName banners
*/
class Banner extends DomArObject {
	
	/**
	* @orm text
	*/
	public $name;
	/**
	* @orm text
	*/
	public $link;
	/**
	* @orm plugin DomArMedia({autoRename=1r,allowedExtensions={gif,jpg,jpeg,png,swf}})
	*/
	public $banner;
	/**
	* @orm longtext
	*/
	public $code;
	/**
	* @orm text
	*/
	public $moderator;
	/**
	* @orm text
	* @orm validator email
	*/
	public $contactEmail;
	/**
	* @orm longtext
	*/
	public $info;
	
	
	
	
	/**
	* @orm plugin DomArDate(now)
	*/
	public $start;
	/**
	* @orm plugin DomArDate(now)
	*/
	public $end;
	/**
	* @orm char(40)
	* @orm listener afterSet afterSetLocation
	*/
	public $location;
	/**
	 * @orm char(40)
	 */
	private $group;
	/**
	* @orm bool
	*/
	public $active = true;
	
	/**
	* @orm bool
	*/
	public $onWeekDay1 = true;
	/**
	* @orm bool
	*/
	public $onWeekDay2 = true;
	/**
	* @orm bool
	*/
	public $onWeekDay3 = true;
	/**
	* @orm bool
	*/
	public $onWeekDay4 = true;
	/**
	* @orm bool
	*/
	public $onWeekDay5 = true;
	/**
	* @orm bool
	*/
	public $onWeekDay6 = true;
	/**
	* @orm bool
	*/
	public $onWeekDay7 = true;
	
	/**
	* Values [0 - not used, 2 - on days with paired number, 1 - on days with not paired number.]
	* @orm int(1) 
	*/ 
	public $onPairedDays = NULL;
	
	const STATISTICS_TABLE_NAME = 'banners_statistics';

	
	public function afterSetLocation() {
		$locations = $this->getLocations();
		$this->group = (string)$locations[$this->location]['group'];
	}

	public static function getLocations() {
		return array(
			'header' => BannerLocation::c()
				->name('Header')
				->group('main')
				->handleMultiple('random')
				->minWidth(200)
				->maxWidth(200)
				->minHeight(200)
				->maxHeight(200)
				->defaultWidth(200)
				->defaultHeight(200)
				->maxSize(200)
				->color('red'),
			'footer' => BannerLocation::c()
				->name('Footer')
				->group('main')
				->handleMultiple('random')
				->minWidth(200)
				->maxWidth(200)
				->minHeight(200)
				->maxHeight(200)
				->defaultWidth(200)
				->defaultHeight(200)
				->maxSize(200)
				->color('orange'),
			'subsite' => BannerLocation::c()
				->name('SubSite')
				->group('sub')
				->handleMultiple('random')
				->minWidth(200)
				->maxWidth(200)
				->minHeight(200)
				->maxHeight(200)
				->defaultWidth(200)
				->defaultHeight(200)
				->maxSize(200)
				->color('blue'),
		);
	}

	public static function getLocationsList() {
		$locations = self::getLocations();
		foreach( $locations as &$location ) {
			$location = array('name'=>$location->name,'style'=>'color:'.$location->color);
		}
		return $locations;
	}
	
	public function createStatisticsTable() {
		
		DomSql::query('
			CREATE TABLE '.self::STATISTICS_TABLE_NAME.' (
				id INT(11) PRIMARY KEY AUTO_INCREMENT,
				datetime DATETIME,
				banner INT(11)
			) ENGINE = MyIsam
		');
		
	}
	
	public function click() {
		if( DomBrowser::isSearchEngineBot() == false ) {
			DomSql::query('INSERT INTO '.self::STATISTICS_TABLE_NAME.' (datetime, banner) VALUES (NOW(),'.(int)$this->id.') ');
		}
		header('Location:'.$this->link);
	}

	
	
	public function getBannerHtml( $clickLink ) {
		if( trim($this->code) ) {
			$html = $this->code;
			
		} else {
			$locations = self::getLocations();
			$html = $this->banner->toHtml( 
				array(
					'width'=>$locations[$this->location]['defaultWidth'], 
					'height'=>$locations[$this->location]['defaultHeight'], 
					'target'=>'_blank', 
					'link'=> $this->link ? $clickLink . $this->id : NULL, 
				) 
			);
		}
		return $html;
	}
	/**
	 * Click link is the link to where user is directed when banner is clicked, but not the final destinaion, but statistics saving destination.
	 * Something like http://yoursite.com/bannerClick/ . Banner ID is put at the end of this url.
	 * @param String $clickLink
	 */
	private function cachePublicBanners( $group, $clickLink ) {

		$banners = BannersQuery::c()->onlyForDate( strtotime('now') )->onlyPublic()->onlyGroup($group)->commit()->toArray();

		$locations = self::getLocations();
		$shown = array();
		foreach( $banners as $banner ) {
			
			$contents = array(
				'id' => $banner->id,
				'html' => $banner->getBannerHtml( $clickLink ),
			);
			
			$shown['__dat'][$banner->location] = array(
				'handleMultiple' => $locations[$banner->location]['handleMultiple'],
			);
			$shown[$banner->location][] = $contents;
		}
		DomCache::cache('Banners_'.$group, $shown, 60);
	}
	/**
	 * Returns array where key is location and value banner html
	 *
	 * @param String $group
	 * @return Array
	 */
	public static function initPublicBanners( $group, $clickLink ) {
		// check that we have active banner cache
		//if( DomCache::isCached('Banners_'.$group) == false )
			self::cachePublicBanners( $group, $clickLink );
		
			
		// load banners
		$list = DomCache::get('Banners_'.$group);
		if( !is_array( $list ) )
			return array();
		
		$resultSet = array();
		foreach( $list as $location => $banners ) {
			
			if( $location == '__dat' )
				continue;
		
			// choose one banner randomly
			if( $list['__dat'][$location]['handleMultiple'] == 'random' ) {
				
				$banner = $banners[array_rand($banners,1)];
				$html = $banner['html'];
			
			
			// put all banners into a list	
			} else if( $list['__dat'][$location]['handleMultiple'] == 'all' ) {
				
				$html = array();
				foreach( $banners as $banner )
					$html[] = $banner['html'];
			}
			
			$resultSet[$location] = $html;
		}
		return $resultSet;
		
	}
	/**
	 * Returns array where key is location and value is highlighted banner location with name in it. 
	 * Might be useful to show all banner locations and their names straight on website.
	 *
	 * @param String $group
	 * @return Array
	 */
	public static function initLocationsHighlight( $group ) {
		$resultSet = array();
		foreach( self::getLocations() as $key => $location ) {
			if( $group == $location['group'] ) {
				$resultSet[$key] = '<div style="width:'.(int)($location['defaultWidth']-4).'px; height:'.(int)($location['defaultHeight']-0).'px; overflow:hidden; background-color:lightblue; font-size:12px; font-weight:bold; color:black; font-family:Verdana; vertical-align:middle; display:table-cell;  padding: 5px 2px 2px 2px; text-align:center;"><p>'.$location['name'].'</p></div>';
			}
		}
		return $resultSet;
	}
	
	
	
	
	public function getDayStatistics( $days = 60 ) {
		$dates = DomSql::keyListQuery('SELECT DATE(datetime) as date, count(*) as clicks FROM '.Banner::STATISTICS_TABLE_NAME.' WHERE banner = '.$this->id.' AND datetime > \''.date('Y-m-d',strtotime('-'.$days.' days')).'\' GROUP BY DATE(datetime)','date')->toArray();
		$max = 1;
		$list = array();
		for( $i=0; $i<$days; $i++) {
			$date = date('Y-m-d',strtotime('-'.$i.' days'));
			$list[$date] = array('date' => $date, 'clicks'=>(int)$dates[$date]['clicks']);
			if( $dates[$date]['clicks'] > $max) {
				$max = $dates[$date]['clicks'];
			}
		}
		return array($list, $max);
	}
	
	public function getHourStatistics() {
		$dates = DomSql::keyListQuery('SELECT HOUR(datetime) as hour, count(*) as clicks FROM '.Banner::STATISTICS_TABLE_NAME.' WHERE banner = '.$this->id.' GROUP BY HOUR(datetime)','hour')->toArray();
		$max = 1;
		$list = array();
		for( $hour=0; $hour<24; $hour++) {
			$list[$hour] = array('hour' => ($hour<10 ? '0'.$hour : $hour), 'clicks'=>(int)$dates[$hour]['clicks']);
			if( $dates[$hour]['clicks'] > $max) {
				$max = $dates[$hour]['clicks'];
			}
		}
		return array($list, $max);
	}
	
	public function getDayOfWeekStatistics() {
		$dates = DomSql::keyListQuery('SELECT DATE_FORMAT(datetime,"%w")+1 as dayOfWeek, count(*) as clicks FROM '.Banner::STATISTICS_TABLE_NAME.' WHERE banner = '.$this->id.' GROUP BY dayOfWeek','dayOfWeek')->toArray();
		$max = 1;
		$list = array();
		$days = array(1=>'Pühapäev','Esmaspäev','Teisipäev','Kolmapäev','Neljapäev','Reede','Laupäev');
		for( $dayOfWeek=1; $dayOfWeek<=7; $dayOfWeek++) {
			$list[$dayOfWeek] = array('day' => $days[$dayOfWeek], 'clicks'=>(int)$dates[$dayOfWeek]['clicks']);
			if( $dates[$dayOfWeek]['clicks'] > $max) {
				$max = $dates[$dayOfWeek]['clicks'];
			}
		}
		return array($list, $max);
	}
	
}
?>